package baseFx.springboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod;

public class FxRequestMappingHandlerAdapter extends RequestMappingHandlerAdapter {
    @Autowired
    private MvcEvents handlerEvents;

    @Override
    protected ServletInvocableHandlerMethod createInvocableHandlerMethod(HandlerMethod handlerMethod) {
        if(handlerMethod.getMethod().getDeclaringClass().getTypeName().contains(".springframework.boot.")){
            return super.createInvocableHandlerMethod(handlerMethod);
        }
        return new ServletInvocableHandlerMethod(handlerMethod) {
            @Override
            protected Object doInvoke(Object... params) throws Exception {
                ActionEventArgs args = new ActionEventArgs(getBean(), getMethod());
                try {
                    handlerEvents.onActionBefore(args);
                    if (args.result == null) {
                        args.result = super.doInvoke(params);
                    }
                    handlerEvents.onActionAfter(args);
                } catch (Exception e) {
                    ActionErrorEventArgs eArgs = new ActionErrorEventArgs(getBean(), getMethod(), e);
                    if (eArgs.result == null) {
                        handlerEvents.onActionError(eArgs);
                    }
                    if (eArgs.result != null) {
                        args.result = eArgs.result;
                    } else {
                        throw e;
                    }
                }
                return args.result;
            }
        };
    }
}
